/*
 * FairyCombineResource.cpp
 *
 *  Created on: 2014. 4. 29.
 *      Author: mega
 */

#include "../macro.h"
#include <algorithm>
#include <Database/Static.h>
#include <Toolkit/Str.h>
#include "FairyCombineResource.h"

namespace ProjectZ { namespace NResource {

FairyCombineResource::FairyCombineResource()
{
}

FairyCombineResource::~FairyCombineResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](FAIRYCOMBINETREE::value_type & pair) {
		delete pair.second;
	});
}

void
FairyCombineResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](FAIRYCOMBINETREE::value_type & pair) {
		delete pair.second;
	});
	clsFlyTree.clear();
}

bool
FairyCombineResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_fairy_combine");

	if (false == ::Database::GETSESSION()->SyncExecute(static_cast<int>(DatabaseType::GAME_MASTER), clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		::Toolkit::Str<200> DESC;

		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_TYPE >> pFly->_ADD_PER >> pFly->_DEFAULT_RATE >> pFly->_EVENT_RATE >> DESC;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_TYPE] = pFly;
	}

	return true;
}

int
FairyCombineResource::GetSuccessType(int & exp)
{
	/*
	 * 성공 타입 계산
	 * 1: 성공, 2: 대성공(1.5배), 3: 초 대성공(2배)
	 */
	int succType = 1;
	int accRate = 0;
	int randRate = rand() % 1000;

	auto iter = clsFlyTree.begin();

	for (; iter != clsFlyTree.end(); ++iter)
	{
		accRate += iter->second->_DEFAULT_RATE;

		if (randRate <= accRate)
		{
			succType = iter->second->_TYPE;
			exp = (exp * iter->second->_ADD_PER) / 100;
			break;
		}
	}

	return succType;
}

} /* namespace NResource */ } /* namespace ProjectZ */
